<script lang="ts" setup>
import { addCardAPI, editCardAPI, getCardDetailAPI, renewCardAPI } from '@/apis/card';
import type { AddCardParams, CardDetailType, RechargeParamsType } from '@/types/card';
import { dayjs, ElMessage,type FormInstance, type FormRules } from 'element-plus';
import { nextTick, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter()
const route = useRoute()

// 车辆信息参数 -----------------------------------
const carForm = ref<Partial<AddCardParams>>({
  personName:'', // 车主姓名
  phoneNumber:'', // 联系方式
  carNumber:'', // 车牌号码
  carBrand:'' // 车辆品牌
})
// 车辆信息表单验证规则
const carFormRules = ref<FormRules<AddCardParams>>({
  personName: [
    { required: true, message: '请输入车主姓名', trigger: 'blur'  }
  ],
  phoneNumber: [
    { required: true, message: '请输入联系方式', trigger: 'blur'  },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  carNumber: [
    { required: true, message: '请输入车牌号码', trigger: 'blur'  },
    { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/, message: '请输入正确的车牌号码', trigger: 'blur'  }
  ],
  carBrand: [
    { required: true, message: '请输入车辆品牌', trigger: 'blur'  }
  ]
})

// 缴费信息参数 ------------------------------------
const feeForm = ref<Partial<AddCardParams>>({
  cardStartDate: '', // 有效日期
  cardEndDate: '', // 有效日期
  paymentAmount: '', // 缴费金额
  paymentMethod: 'Alipay' // 支付方式
})
// 校验规则缴费信息
const feeFormRules = ref<FormRules<AddCardParams>>({
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'blur'  }
  ],
  cardEndDate: [
    { required: true, message: '请选择有效日期', trigger: 'blur'  }
  ],
  paymentAmount: [
    { required: true, message: '请输入缴费金额', trigger: 'blur'  },
    { pattern: /^[1-9]\d*(\.\d{1,2})?$/, message: '请输入正确的金额', trigger: 'blur'  }
  ]
})
// 支付方式
const payMethodList = [
  { id: 'Alipay', name: '支付宝' },
  { id: 'WeChat', name: '微信' },
  { id: 'Cash', name: '线下' }
]
// 日期
const cardDateArr = ref<string[]>([])

// 监听日期变化，处理数据
watch(cardDateArr, (val) => {
  if (val) {
    feeForm.value.cardStartDate = val[0]
    feeForm.value.cardEndDate = val[1]
  } else {
    feeForm.value.cardStartDate = ''
    feeForm.value.cardEndDate = ''
  }
}, { deep: true })

const carInfoRef = ref<FormInstance>()
const feeRef = ref<FormInstance>()
// 提交表单
const loadingFlag = ref(false)

const onSubmit = async () => {
  await Promise.all([carInfoRef.value?.validate(), feeRef.value?.validate()])

  loadingFlag.value = true
  try {
    if (!route.params.id) {
      // 新增月卡
      await addCardAPI({
        ...carForm.value,
        ...feeForm.value
      })
      ElMessage.success('添加成功')
      router.back()
    } else {
      if (route.query.type) {
        // 续费月卡 -----------
        // 参数
        const data: RechargeParamsType = {
          ...feeForm.value,
          carInfoId: carInfoId.value
        } as RechargeParamsType
        await renewCardAPI(data)
        ElMessage.success('续费成功')
        router.back()
      } else {
        // 编辑月卡 -----------
        const res = await editCardAPI({
          ...carForm.value,
          ...feeForm.value,
          carInfoId: carInfoId.value,
          rechargeId: rechargeId.value
        } as CardDetailType)

        if(res.code === 10000) {
          ElMessage.success('编辑成功')
        } else {
          ElMessage.error(res.msg)
        }
        router.back()
      }
    }
  } catch (error) {
    loadingFlag.value = false
  }
}

// 编辑回显数据 ----------------------- 续费
const carInfoId = ref<number>(0) // 车辆信息id
const rechargeId = ref<number>(0) // 充值记录id
const cardEndDate = ref<string>('') // 有效时间结束--暂存
const editData = async () => {
  if (!route.params.id) return
  const res = await getCardDetailAPI(+route.params.id)
  // 回显基本数据
  carForm.value.personName = res.data.personName // 车主姓名
  carForm.value.phoneNumber = res.data.phoneNumber // 联系号
  carForm.value.carNumber = res.data.carNumber // 车牌号
  carForm.value.carBrand = res.data.carBrand // 车辆品牌
  feeForm.value.paymentAmount = res.data.paymentAmount // 缴费金额
  cardDateArr.value = [res.data.cardStartDate, res.data.cardEndDate] // 有效日期
  feeForm.value.paymentMethod = res.data.paymentMethod // 支付方式
  carInfoId.value = res.data.carInfoId // 车辆信息id
  rechargeId.value = res.data.rechargeId // 充值记录id
  cardEndDate.value = res.data.cardEndDate // 有效时间结束
  // 续费页面回显指定时间
  if (route.query.type) {
    // 存储当前时间
    nextTick(() => {
      const formatDate = +new Date() // 当前时间
      const endDate = +new Date(res.data.cardEndDate) + 24 * 60 * 60 * 1000 // 有效时间结束 + 1天
      const flag = endDate > formatDate // 有效时间结束是否大于当前时间

      feeForm.value.cardStartDate = flag ? dayjs(endDate).format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD')
      feeForm.value.cardEndDate = ''
    })
  }
}
editData()

// 重置表单 ---------------------------------
const resetFrom = () => {
  feeForm.value.cardEndDate = ''
  feeForm.value.paymentAmount = ''
  feeForm.value.paymentMethod = 'Alipay'
  // 单独清除一个校验
  feeRef.value?.resetFields('cardEndDate')
  feeRef.value?.resetFields('paymentAmount')
  // 判断是否不是编辑或者续费
  if (!route.params.id) {
    carForm.value.carNumber = ''
    carInfoRef.value?.resetFields('carNumber')
    
  }
  // 判断是否不是续费
  if (!route.query.type) {
    carForm.value.personName = ''
    carInfoRef.value?.resetFields('personName')
    carForm.value.phoneNumber = ''
    carInfoRef.value?.resetFields('phoneNumber')
    carForm.value.carBrand = ''
    carInfoRef.value?.resetFields('carBrand')
    cardDateArr.value = []
  }
}

// 设置日期范围 ---------------------------
const disabledDate = (time: any) => {
  // 获取指定日期的时间戳
  const formatDate = +new Date() // 当前时间
  const endDate = +new Date(cardEndDate.value) + 24 * 60 * 60 * 1000 // 有效时间结束 + 1
  const flag = endDate > formatDate // 有效时间结束是否大于当前时间

  const currentTime = flag ? endDate : formatDate

  return time.getTime() < currentTime
}
</script>

<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header :content="$route.query.type ? '续费月卡' : $route.params.id ? '编辑月卡' : '新增月卡'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form" >
          <el-form ref="carInfoRef" :model="carForm" :rules="carFormRules" label-width="100px">
            <el-form-item label="车主姓名" prop="personName">
              <el-input v-model="carForm.personName" :disabled="!!$route.query.type" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="carForm.phoneNumber" :disabled="!!$route.query.type" maxlength="11" />
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <el-input maxlength="8" :disabled="!!$route.params.id" v-model="carForm.carNumber" />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model="carForm.carBrand" :disabled="!!$route.query.type" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <div class="form">
          <el-form ref="feeRef" :model="feeForm" :rules="feeFormRules" label-width="100px">
            <el-form-item label="有效日期" prop="cardEndDate">
              <!-- 续费日期 -->
              <template v-if="$route.query.type">
                <el-date-picker
                  v-model="feeForm.cardStartDate"
                  type="date"
                  placeholder="哈哈哈哈哈哈"
                  disabled
                />
                <span style="padding: 0 10px;">-</span>
                <el-date-picker
                  v-model="feeForm.cardEndDate"
                  type="date"
                  placeholder="零基础学IT,就来黑马程序员"
                  :disabled-date="disabledDate"
                />
              </template>
              <!-- 其他情况日期 -->
              <template v-else>
                <el-date-picker
                  v-model="cardDateArr"
                  value-format="YYYY-MM-DD" 
                  type="daterange" 
                  ange-separator="至" 
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </template>
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input v-model="feeForm.paymentAmount" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="feeForm.paymentMethod" >
                <el-option v-for="item in payMethodList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>

    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetFrom">重置</el-button>
        <el-button type="primary" @click="onSubmit" :loading="loadingFlag">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }

    .preview {
      img {
        width: 100px;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>